<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="mini" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="客户编号" prop="customerNo">
        <el-input v-model="queryParams.customerNo" placeholder="请输入客户编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="客户名称" prop="customerName">
        <el-input v-model="queryParams.customerName" placeholder="请输入客户名称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="公司名称" prop="companyName">
        <el-input v-model="queryParams.companyName" placeholder="请输入公司名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="客户类型" prop="customerType">
        <el-select v-model="queryParams.customerType" placeholder="请选择客户类型" clearable>
          <el-option v-for="dict in dict.type.erp_customer_type" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['erp:ErpCustomer:add']">新增客户</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['erp:ErpCustomer:export']">列表导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ErpCustomerList" row-key="customerId" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" align="center" :reserve-selection="true" width="40px" />
      <el-table-column label="客户编号" align="center" prop="customerNo" sortable width="180px;"/>
      <el-table-column label="客户名称" align="center" prop="customerName" width="250px;"/>
      <el-table-column label="公司名称" align="center" prop="companyName" width="250px;"/>
      <el-table-column label="客户类型" align="center" prop="customerType" sortable width="100px;">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.erp_customer_type" :value="scope.row.customerType" />
        </template>
      </el-table-column>
      <el-table-column label="客户等级" align="center" prop="customerLevel" sortable width="100px;">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.erp_customer_level" :value="scope.row.customerLevel" />
        </template>
      </el-table-column>
      <!--<el-table-column label="营业性质" align="center" prop="customerNature" width="80px;">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.erp_customer_nature" :value="scope.row.customerNature" />
        </template>
      </el-table-column>-->
      <!--<el-table-column label="所属行业" align="center" prop="customerIndustry" width="100px;">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.erp_customer_industry" :value="scope.row.customerIndustry" />
        </template>
      </el-table-column>-->
      <el-table-column label="统一信用代码" align="center" prop="unifiedCode" sortable width="150px;"/>
      <el-table-column label="法人代表" align="center" prop="legalRepresentative" width="80px;"/>
      <el-table-column label="联系人" align="center" prop="linkman" width="80px;"/>
      <el-table-column label="联系电话" align="center" prop="linkmanPhone" width="120px;"/>
      <el-table-column label="所在地区" align="center" prop="province" sortable width="160px;">
        <template slot-scope="scope">
          {{ scope.row.province + '/' +  scope.row.city + '/' + scope.row.county}}
        </template>
      </el-table-column>
      <el-table-column label="详细地址" prop="address" />
      <el-table-column label="审批状态" align="center" prop="approveStatus" sortable width="100px;">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.approveStatus == 0" type="primary">待审核</el-tag>
          <el-tag v-if="scope.row.approveStatus == 1" type="success">已通过</el-tag>
          <el-tag v-if="scope.row.approveStatus == 2" type="danger">被驳回</el-tag>
          <el-tooltip v-if="scope.row.approveStatus == 2" effect="light" placement="bottom">
            <div slot="content">
              {{ scope.row.rejectReason }}
            </div>
            <i class="el-icon-warning-outline" style="margin-left: 5px; color: red;"></i>
          </el-tooltip>
        </template>
      </el-table-column>
      <!--<el-table-column align="center" label="审批时间" prop="approveTime" width="160px;">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.approveTime) }}</span>
        </template>
      </el-table-column>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="160px;">
        <template slot-scope="scope">
          <el-button v-if="scope.row.approveStatus == 0 || scope.row.approveStatus == 2" size="mini" type="text" @click="handleAuditOptions(scope.row, 1)"
            v-hasPermi="['erp:ErpCustomer:audit']">通过</el-button>
          <el-button v-if="scope.row.approveStatus == 0" size="mini" type="text" @click="handleAuditOptions(scope.row, 2)"
            v-hasPermi="['erp:ErpCustomer:audit']">驳回</el-button>
          <el-button size="mini" type="text" @click="handleUpdate(scope.row)"
            v-hasPermi="['erp:ErpCustomer:edit']">修改</el-button>
          <el-button size="mini" type="text" @click="handleDelete(scope.row)"
            v-hasPermi="['erp:ErpCustomer:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改客户管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" size="mini" label-width="110px">
        <el-row>
          <!--<el-col :span="12">
            <el-form-item label="客户编号" prop="customerNo">
              <el-input v-model="form.customerNo" :disabled="true" placeholder="请输入" />
            </el-form-item>
          </el-col>-->
          <el-col :span="24">
            <el-form-item label="公司名称" prop="companyName">
              <el-input v-model="form.companyName" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="客户名称" prop="customerName">
              <el-input v-model="form.customerName" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户类型" prop="customerType">
              <el-select v-model="form.customerType" placeholder="请选择客户类型">
                <el-option v-for="dict in dict.type.erp_customer_type" :key="dict.value" :label="dict.label"
                           :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="客户等级" prop="customerLevel">
              <el-select v-model="form.customerLevel" placeholder="请选择客户等级">
                <el-option v-for="dict in dict.type.erp_customer_level" :key="dict.value" :label="dict.label"
                           :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="折扣" prop="discount">
              <el-input v-model="form.discount" placeholder="请输入" type="number">
                <template slot="append"></template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="营业性质" prop="customerNature">
              <el-select v-model="form.customerNature" placeholder="请选择">
                <el-option v-for="dict in dict.type.erp_customer_nature" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属行业" prop="customerIndustry">
              <el-select v-model="form.customerIndustry" placeholder="请选择所属行业">
                <el-option v-for="dict in dict.type.erp_customer_industry" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="所在地区" prop="location">
              <el-cascader placeholder="请选择" v-model="form.location" :options="addressOptions"
                @change="handleLocationChange" :props="{ value: 'label' }"></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="详细地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="法人代表" >
              <el-input v-model="form.legalRepresentative" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="统一信用代码" >
              <el-input v-model="form.unifiedCode" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系人" prop="linkman">
              <el-input v-model="form.linkman" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="linkmanPhone">
              <el-input v-model="form.linkmanPhone" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="公司电话" prop="companyPhone">
              <el-input v-model="form.companyPhone" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="微信账号" prop="weixin">
              <el-input v-model="form.weixin" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" v-model="form.remark"
                placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listErpCustomer, getErpCustomer, delErpCustomer, addErpCustomer, updateErpCustomer, auditErpCustomer } from "@/api/erp/ErpCustomer";
import addressOptions from '@/assets/address.json'
import { checkSocialCreditCode } from '@/utils/validataForm'
export default {
  name: "ErpCustomer",
  dicts: ['erp_customer_type', 'erp_customer_industry', 'erp_customer_nature','erp_customer_level'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 客户管理表格数据
      ErpCustomerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        customerNo: null,
        customerName: null,
        companyName: null,
        customerType: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        customerName: [
          { required: true, message: "客户名称不能为空", trigger: "blur" }
        ], companyName: [
          { required: true, message: "公司名称不能为空", trigger: "blur" }
        ], customerType: [
          { required: true, message: "客户类型不能为空", trigger: "blur" }
        ], location: [
          { required: true, message: "所在地区不能为空", trigger: "blur" }
        ], address: [
          { required: true, message: "详细地址不能为空", trigger: "blur" }
        ], legalRepresentative: [
          { required: true, message: "法人代表不能为空", trigger: "blur" }
        ], unifiedCode: [
          { required: true, validator: checkSocialCreditCode, trigger: "blur" }
        ], linkman: [
          { required: true, message: "联系人名称不能为空", trigger: "blur" }
        ], linkmanPhone: [
          { required: true, message: "联系人电话不能为空", trigger: "blur" }
        ],
      },
      // 省市区选择
      addressOptions: addressOptions
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询客户管理列表 */
    getList() {
      this.loading = true;
      listErpCustomer(this.queryParams).then(response => {
        this.ErpCustomerList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 所在地区选择 */
    handleLocationChange(e) {
      console.log(e);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        customerNo: "KH" + this.parseTime(new Date(), '{y}{m}{d}{h}{i}{s}'),
        customerName: null,
        companyName: null,
        customerType: null,
        customerLevel: null,
        customerNature: null,
        customerIndustry: null,
        discount:1,
        province: null,
        city: null,
        county: null,
        address: null,
        legalRepresentative: null,
        unifiedCode: null,
        linkman: null,
        linkmanPhone: null,
        companyPhone: null,
        weixin: null,
        remark: null,
        createId: null,
        createName: null,
        createTime: null,
        flag: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.customerId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加客户";

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const customerId = row.customerId || this.ids
      getErpCustomer(customerId).then(response => {
        this.form = response.data;
        this.form.location = [];
        this.form.location.push(this.form.province)
        this.form.location.push(this.form.city)
        this.form.location.push(this.form.county)
        this.open = true;
        this.title = "修改客户";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.province = this.form.location[0];
          this.form.city = this.form.location[1];
          this.form.county = this.form.location[2];
          if (this.form.customerId != null) {
            updateErpCustomer(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addErpCustomer(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const customerIds = row.customerId || this.ids;
      this.$modal.confirm('是否确认删除客户管理编号为"' + customerIds + '"的数据项？').then(function () {
        return delErpCustomer(customerIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('erp/ErpCustomer/export', {
        ...this.queryParams,
        exportIds: this.ids?.join(',')
      }, `客户信息_${new Date().getTime()}.xlsx`)
    },
    /** 审核or驳回 */
    handleAuditOptions(row, type) {
      this.form = {
        approveStatus: type,
        customerId: row.customerId
      }
      if (type == 2) {
        this.$prompt('', '驳回原因', {
          center: true,
          inputType: 'textarea',
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(({value}) => {
          this.form.rejectReason = value;
          this.handleAudit();
        })
      } else {
        this.handleAudit();
      }
    },
    // 审核提交
    handleAudit() {
      auditErpCustomer(this.form).then(res => {
        this.$modal.msgSuccess("操作成功");
        this.open = false;
        this.getList();
      })
    },
  }
};
</script>
<style scoped>
.el-select {
  width: 100%;
}

.el-cascader {
  width: 100%;
}
</style>
